from asyncio import get_event_loop, ensure_future

from aiomysql import create_pool, DictCursor

from tools.ini_reader import IniReader
from setting import DATABASE_INI_PATH


class DataBase:
    def __init__(
        self, database: str = "mysql", autocommit: bool = True, *args, **kwargs
    ):
        self._args, self._kwargs = args, kwargs
        self._autocommit = autocommit
        if database.lower() == "mysql":
            self._database = create_pool
            self._ini = IniReader(DATABASE_INI_PATH).data
            self._loop = get_event_loop()
            self._mysql_pool = self.mysql_pool

    @property
    def mysql_pool(self):
        self._ini["autocommit"] = self._autocommit
        pool_task = ensure_future(
            self._database(*self._args, **self._ini, **self._kwargs)
        )
        self._loop.run_until_complete(pool_task)
        return pool_task.result()


class MySQLClient(DataBase):
    @classmethod
    def setup(cls, *args, **kwargs):
        return cls(*args, **kwargs)

    async def _select(self, sql: str, param: tuple = (), rows: [int, None] = 1):
        async with self._mysql_pool.acquire() as conn:
            async with conn.cursor(DictCursor) as cur:
                await cur.execute(sql.replace("?", "%s"), param)
                if rows:
                    result = await cur.fetchmany(rows)
                else:
                    result = await cur.fetchall()

        return result

    def select(self, *args, **kwargs):
        self._loop.run_until_complete(
            select_task := ensure_future(self._select(*args, **kwargs))
        )
        return select_task.result()

    async def _execute(self, sql: str, param: tuple = ()):
        async with self._mysql_pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute(sql.replace("?", "%s"), param)
                return cur.rowcount

    def execute(self, *args, **kwargs):
        self._loop.run_until_complete(
            execute_task := ensure_future(self._execute(*args, **kwargs))
        )
        return execute_task.result()


if __name__ == "__main__":
    mysql = MySQLClient.setup()
    # print(mysql.select(r'SHOW DATABASES', rows=None))
    # print(mysql.select(r'SELECT * FROM scm_db_dev.bid_scoring_member', rows=None))
    # 带参数
    # print(mysql.select(r'SELECT * FROM bid_scoring_member WHERE id=?', (2, )))
    # 需要 commit 的 SQL
    # print(mysql.execute(r'UPDATE bid_scoring_member SET template_id=? WHERE id=?', (1, 2)))
    sql1 = (
        "SELECT id FROM scm_purchase_apply_b "
        "WHERE details_status='WaitPurchase' "
        "AND inquiry_progress = 'inactive' LIMIT 10;"
    )
    print(mysql.select(sql1))
